using System;
using System.ComponentModel;
using System.Data;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Diagnostics;
using Microsoft.Practices.ObjectBuilder2;
using Common.Unity.Extensions;

namespace Common.Unity.Extensions.Entity
{
	class EntityRetrievalPolicy : EntityCreationPolicyBase
	{
		public EntityRetrievalPolicy( ObjectContext context, IEntityCreator creator	) : base( context, creator )
		{}

		protected override object RetrieveExistingEntity( IBuilderContext context )
		{
			Type type;
			if ( BuildKey.TryGetType( context.BuildKey, out type ) && typeof(IEntityWithKey).IsAssignableFrom( type ) )
			{
				var source = context.GetBuildSource();
				if ( source != null )
				{
					var key = source is EntityKey ? (EntityKey)source : MetadataHelper.ExtractKey( EntityContext, type, source );
					if ( key != null )
					{
						object result;
						return ( EntityContext.TryGetObjectByKey( key, out result ) ? result : null ) as IEntityWithKey;
					}
				}
			}
			return null;
		}
	}
}